package com.wangl.spring.service;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.wangl.spring.suggestion.PropertiesManager;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ProjectSuggestionService
 * @Description TODO
 * @Author wangl
 * @Date 2023/3/31 13:17
 */
public class ProjectSuggestionService {

    private final Project project;
    private final PropertiesManager propertiesManager;

    public ProjectSuggestionService(Project project) {
        this.project = project;
        this.propertiesManager = new PropertiesManager();
    }

    public void reIndex() {
        List<Module> modules = Arrays.stream(ModuleManager.getInstance(project).getModules())
                .filter(module -> module.getName().contains(".main"))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(modules)){
            reIndex(Arrays.stream(ModuleManager.getInstance(project).getModules())
                    .toArray(Module[]::new));
        }else {
            reIndex(modules.toArray(new Module[0]));
        }
    }

    public void reIndex(Module[] modules) {
        List<Module> moduleList = Arrays.stream(modules)
                .filter(module -> module.getName().contains(".main"))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(moduleList)){
            moduleList = Arrays.stream(modules).collect(Collectors.toList());
        }
        for (Module module : moduleList) {
            module.getService(SuggestionService.class).reIndex();
        }
    }

    public PropertiesManager getPropertiesManager() {
        return propertiesManager;
    }
}
